package com.java.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.java.dao.ActivityReviewDao;
import com.java.domain.ActivityReview;
import com.java.domain.event.ActivityReviewEvent;
import com.java.service.ReviewService;
import com.java.service.SportService;
import com.java.service.UserService;
import com.java.util.MyTools;
import com.java.util.resp.BaseRespone;
import com.java.util.resp.TableRespone;

@Service
public class ReviewServiceImpl implements ReviewService {
	
	@Resource ActivityReviewDao reviewDao;
	@Resource SportService sportService;
	@Resource UserService userService;

	@Override
	public BaseRespone saveReview(String userId, String sportId, String reviewText) {
		ActivityReview info = new ActivityReview();
		info.setReviewId(MyTools.getUUID())
		.setReviewSportId(sportId)
		.setReviewUserId(userId)
		.setReviewText(reviewText)
		.setReviewTime(new Date());
		int row = reviewDao.insertSelective(info);
		return BaseRespone.result(row, "Review Success");
	}

	@Override
	public BaseRespone replyReview(String reviewId, String replyText) {
		ActivityReview info = new ActivityReview();
		info.setReviewId(reviewId)
		.setReviewReply(replyText)
		.setReviewReplyTime(new Date());
		int row = reviewDao.updateSelective(info);
		return BaseRespone.result(row, "Reply Success");
	}

	@Override
	public BaseRespone delReview(String reviewId) {
		int row = reviewDao.deleteByKey(reviewId);
		return BaseRespone.result(row, "Delete Success");
	}

	@Override
	public TableRespone getReviewsBySport(String sportId, int page, int size) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("reviewSportId", sportId);
		List<ActivityReviewEvent> list = reviewDao.selectAll(params, page, size);
		plugReviews(list);
		long total = reviewDao.selectAllCount(params);
		return new TableRespone(list, total);
	}

	@Override
	public TableRespone getReviewsByUser(String userId, int page, int size) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("reviewUserId", userId);
		List<ActivityReviewEvent> list = reviewDao.selectAll(params, page, size);
		plugReviews(list);
		long total = reviewDao.selectAllCount(params);
		return new TableRespone(list, total);
	}

	private void plugReviews(List<ActivityReviewEvent> list) {
		if(!MyTools.isEmpty(list)) {
			for (ActivityReviewEvent review : list) {
				review.setSport(sportService.getOne(review.getReviewSportId()));
				review.setUser(userService.getUserById(review.getReviewUserId()));
			}
		}
	}
}
